var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
// @ts-ignore
var __NativeVar__;
// @ts-ignore
var __NativeVar2__;
// @ts-ignore
var __NativeVar3__;
// @ts-ignore
var Wab;
// @ts-ignore
var Wabo = /** @class */ (function () {
    function Wabo() {
        // Counter of callback ids, randomized to avoid
        // any issues during reloads if a call comes back with
        // an existing callback id from an old session
        this.replyIdCount = Math.floor(Math.random() * 134217728);
        this.__replys__ = {};
        this.__listeners = [];
    }
    Object.defineProperty(Wabo.prototype, "messageListeners", {
        get: function () {
            return this.__listeners;
        },
        enumerable: false,
        configurable: true
    });
    Wabo.prototype.addMessageListener = function (listener) {
        this.__listeners.push(listener);
    };
    Wabo.prototype.removeMessageListener = function (listener) {
        var index = this.__listeners.indexOf(listener);
        if (index > -1) {
            this.__listeners.splice(index, 1);
        }
    };
    /**
     * native post message handler.
     * @param event MessageEvent
     * @returns void
     */
    Wabo.prototype.onMessage = function (event) {
        console.log("[Wab] onMessage: ", event, event.data);
        if (event.data == "__setupPort__" && event.ports.length > 0) {
            console.log("[Wab] onMessage: __setupPort__", event);
            __NativeVar3__ = event.ports[0];
            __NativeVar3__.addEventListener("message", this.onMessage.bind(this));
            // 使用 EventTarget.addEventListener 需要显式调用 start() 来开始, onmessage 已经隐含调用此方法
            __NativeVar3__.start();
        }
        else {
            if (!event.data) {
                console.warn("[Wab] onMessage: event.data is undefined.", event);
                return;
            }
            try {
                var rb = JSON.parse(event.data);
                this.onReply(rb);
            }
            catch (error) {
                console.error("[Wab] onMessage: MessageHandler error.", error);
            }
            console.log("[Wab] onMessage: MessageHandler proceed.", event);
            this.peelOff(event)();
        }
    };
    /**
     * 洋葱🧅模型
     * @param event
     * @returns
     */
    Wabo.prototype.peelOff = function (event) {
        var that = this;
        return function (next) {
            var index = -1;
            var shouldStop = false;
            var dispatch = function (i) {
                if (i <= index || shouldStop)
                    return Promise.reject(new Error("next() called multiple times or stopped"));
                index = i;
                var fn = that.__listeners[i];
                if (i == that.__listeners.length)
                    fn = next();
                if (!fn)
                    return Promise.resolve();
                try {
                    var stop_1 = function () {
                        shouldStop = true;
                        return;
                    };
                    return Promise.resolve(fn(event, dispatch.bind(null, i + 1), stop_1));
                }
                catch (error) {
                    return Promise.reject(error);
                }
            };
            return dispatch(0);
        };
    };
    Wabo.prototype.getValue = function (options) {
        console.log("[Wab] getValue: ", __NativeVar__, __NativeVar2__, __NativeVar3__);
        console.log("[Wab] getValue: ", options);
        options.type = "value";
        options.preferChannel = 0;
        return this.preferChannel(options).postMessage(JSON.stringify(options));
    };
    Wabo.prototype.getValueAsync = function (options) {
        console.log("[Wab] getValueAsync: ", options);
        options.type = "value";
        if (options.preferChannel == 0) {
            throw "[Wab] getValueAsync: LegacyChannel is not a Promise";
        }
        return this.waitReply(options);
    };
    Wabo.prototype.callFunction = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log("[Wab] callFunction: ", options);
                options.type = "function";
                return [2 /*return*/, this.waitReply(options)];
            });
        });
    };
    Wabo.prototype.waitReply = function (options) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            try {
                var replyId = "-1";
                // store the call for later lookup
                _this.replyIdCount = _this.replyIdCount + 1;
                replyId = String(_this.replyIdCount);
                _this.__replys__[replyId] = { resolve: resolve, reject: reject };
                var callData = __assign({ replyId: replyId }, options);
                var result = _this.preferChannel(options).postMessage(JSON.stringify(callData));
                // @ts-ignore
                if (!result && options.preferChannel == 0) {
                    // @ts-ignore
                    resolve(result);
                }
            }
            catch (error) {
                console.error(error);
                reject(error);
            }
        });
    };
    Wabo.prototype.onReply = function (rb) {
        console.log("[Wab] onReply: ", rb, rb.replyId, rb.replyOnce, rb.error, rb.data);
        if (!rb.replyId) {
            console.warn("[Wab] onReply: no replyId", rb);
            return;
        }
        try {
            var pc = this.__replys__[rb.replyId];
            if (pc) {
                if (!rb.error) {
                    pc.resolve(rb.data);
                }
                else {
                    pc.reject(rb.error);
                }
            }
            else if (rb.error) {
                console.warn(rb.error);
            }
            if (rb.replyOnce == true) {
                delete this.__replys__[rb.replyId];
            }
        }
        catch (e) {
            console.error(e);
        }
        // always delete to prevent memory leaks
        // overkill but we're not sure what apps will do with this data
        delete rb.data;
        delete rb.error;
    };
    /**
     * Destroys the communication bridge between the web page and the native environment.
     */
    Wabo.prototype.destroy = function () {
        window.removeEventListener("message", this.onMessage);
        window.removeEventListener("error", this.onError);
        if (__NativeVar2__ &&
            typeof __NativeVar2__.removeEventListener == "function") {
            __NativeVar2__.removeEventListener("message", this.onMessage);
        }
        if (__NativeVar3__ &&
            typeof __NativeVar3__.removeEventListener == "function") {
            __NativeVar3__.removeEventListener("message", this.onMessage);
        }
    };
    Wabo.prototype.onError = function (event, source, lineno, colno, error) {
        Wab.callFunction({
            type: "function",
            name: "onError",
            replyOnce: true,
            error: {
                event: typeof event == "string" ? event : JSON.stringify(event),
                source: source,
                lineno: lineno,
                colno: colno,
                error: JSON.stringify(error),
            },
        });
    };
    Wabo.prototype.preferChannel = function (options) {
        var _a;
        var preferChannel = (_a = options === null || options === void 0 ? void 0 : options.preferChannel) !== null && _a !== void 0 ? _a : 2;
        var channel = this.selectChannel(preferChannel);
        console.log("[Wab] preferChannel: ", channel, preferChannel, options);
        while (!channel && preferChannel > -1) {
            console.warn("[Wab.postNative] preferChannel=".concat(preferChannel, " is undefined!"));
            preferChannel = preferChannel - 1;
            channel = this.selectChannel(preferChannel);
        }
        return channel;
    };
    Wabo.prototype.selectChannel = function (preferChannel) {
        if (preferChannel === void 0) { preferChannel = 2; }
        return preferChannel == 0
            ? __NativeVar__
            : preferChannel == 1
                ? __NativeVar2__
                : __NativeVar3__;
    };
    return Wabo;
}());
// *****************************************************************************
try {
    Wab = new Wabo();
    // @ts-ignore
    window.Wab = Wab;
    console.log("[start]", Wab);
    Object.freeze(Wab);
    // @ts-ignore
    if (window.__Wab_Listener__) {
        // @ts-ignore
        __NativeVar2__ = window.__Wab_Listener__;
        // @ts-ignore
    }
    if (window.__Wab_Legacy__) {
        // @ts-ignore
        __NativeVar__ = window.__Wab_Legacy__;
    }
    window.addEventListener("message", Wab.onMessage.bind(Wab), false);
    window.addEventListener("error", Wab.onError.bind(Wab), false);
    // startPatch();
}
catch (error) {
    console.error("[Wab] error: " + error);
    throw error;
}
// *****************************************************************************
